package com.exam.serviceimpl;
import com.exam.entity.MultiQuestion;
import com.exam.mapper.MultiQuestionRepository;
import com.exam.service.MultiQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MultiQuestionServiceImpl implements MultiQuestionService {

    @Autowired
    private MultiQuestionRepository multiQuestionRepository;

    @Override
    public MultiQuestion addMultiQuestion(MultiQuestion multiQuestion) {
        if (checkDuplicate(multiQuestion)) {
            throw new IllegalArgumentException("Duplicate multi question exists!");
        }
        return multiQuestionRepository.save(multiQuestion);
    }

    @Override
    public MultiQuestion updateMultiQuestion(Long id, MultiQuestion multiQuestion) {
        MultiQuestion existing = multiQuestionRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Multi question not found!"));
        existing.setSubject(multiQuestion.getSubject());
        existing.setQuestion(multiQuestion.getQuestion());
        existing.setOptions(multiQuestion.getOptions());
        existing.setAnswer(multiQuestion.getAnswer());
        return multiQuestionRepository.save(existing);
    }

    @Override
    public void deleteMultiQuestion(Long id) {
        if (!multiQuestionRepository.existsById(id)) {
            throw new IllegalArgumentException("Multi question not found!");
        }
        multiQuestionRepository.deleteById(id);
    }
//
    @Override
    public MultiQuestion getMultiQuestionById(Long id) {
        return multiQuestionRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Multi question not found!"));
    }

    @Override
    public List<MultiQuestion> getAllMultiQuestions() {
        return multiQuestionRepository.findAll();
    }

    @Override
    public boolean checkDuplicate(MultiQuestion multiQuestion) {
        return multiQuestionRepository
                .findBySubjectAndQuestionAndAnswer(multiQuestion.getSubject(), multiQuestion.getQuestion(), multiQuestion.getAnswer())
                .isPresent();
    }

    @Override
    public void importMultiQuestions(List<MultiQuestion> multiQuestions) {
        for (MultiQuestion multiQuestion : multiQuestions) {
            if (!checkDuplicate(multiQuestion)) {
                multiQuestionRepository.save(multiQuestion);
            }
        }
    }
    @Override
    public Page<MultiQuestion> getAllMultiQuestions(Pageable pageable) {
        return multiQuestionRepository.findAll(pageable);
    }
}